/**
 * API工具函数
 */

/**
 * 统一处理API响应
 * @param {Promise} promise - API请求Promise
 * @param {string} successMessage - 成功提示信息
 * @returns {Promise} 处理后的Promise
 */
export const handleResponse = (promise, successMessage = '操作成功') => {
  return promise
    .then(res => {
      // 显示成功提示
      if (successMessage) {
        uni.showToast({
          title: successMessage,
          icon: 'success',
          duration: 2000
        })
      }
      return res
    })
    .catch(error => {
      // 统一错误处理
      let errorMsg = '操作失败'
      if (error.message) {
        errorMsg = error.message
      } else if (error.errMsg) {
        errorMsg = error.errMsg
      }
      
      uni.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 2000
      })
      
      // 重新抛出错误，让调用者可以进一步处理
      throw error
    })
}

/**
 * 创建带错误处理的API调用函数
 * @param {Function} apiFunction - API函数
 * @param {string} successMessage - 成功提示信息
 * @returns {Function} 带错误处理的API函数
 */
export const withErrorHandling = (apiFunction, successMessage) => {
  return (...args) => handleResponse(apiFunction(...args), successMessage)
}

/**
 * 创建API客户端
 * @param {string} baseURL - 基础URL
 * @returns {Object} API客户端对象
 */
export const createApiClient = (baseURL) => {
  return {
    // GET请求
    get: (url, params = {}, config = {}) => {
      return handleResponse(
        get(url, params, config),
        ''
      )
    },
    
    // POST请求
    post: (url, data = {}, config = {}) => {
      return handleResponse(
        post(url, data, config),
        '创建成功'
      )
    },
    
    // PUT请求
    put: (url, data = {}, config = {}) => {
      return handleResponse(
        put(url, data, config),
        '更新成功'
      )
    },
    
    // DELETE请求
    delete: (url, config = {}) => {
      return handleResponse(
        del(url, config),
        '删除成功'
      )
    },
    
    // 上传文件
    upload: (url, filePath, name, formData = {}, config = {}) => {
      return handleResponse(
        upload(url, filePath, name, formData, config),
        '上传成功'
      )
    },
    
    // 下载文件
    download: (url, config = {}) => {
      return handleResponse(
        download(url, config),
        '下载成功'
      )
    }
  }
}

// 导入HTTP方法
import { 
  request,
  get,
  post,
  put,
  del,
  upload,
  download
} from './request.js'

export default {
  handleResponse,
  withErrorHandling,
  createApiClient,
  request,
  get,
  post,
  put,
  del,
  upload,
  download
}